package com.dddd.blog.blogfile.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.dddd.blog.blogfile.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 喵星球的大橘
 */
@Service
public class UploadServiceImpl implements UploadService {

    @Value("${aliyun.oss.maxSize}")
    private int maxSize;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Value("${aliyun.oss.dir.prefix}")
    private String dirPrefix;

    @Value("${aliyun.oss.urlPrefix}")
    private String urlPrefix;

    @Autowired
    private OSSClient ossClient;


    /**
     * 上传图片
     * @param file
     * @return
     */
    @Override
    public String uploadImage(MultipartFile file) {

        if(file.isEmpty()){
            return "Empty File";
        }
       try{
           String name = file.getOriginalFilename();
           String uuid = UUID.randomUUID().toString().substring(0,11);
           String filename = dirPrefix + uuid + "_" + name;
           PutObjectResult resultObject = ossClient.putObject(bucketName, filename, new ByteArrayInputStream(file.getBytes()));
           System.out.println(resultObject);
           return urlPrefix + "/" + filename;
       }catch (IOException e){
           System.out.println(e.getMessage());
       }finally {
           if(ossClient!=null){
               ossClient.shutdown();
           }
       }
       return "";
    }
}
